<?php
namespace App\Admin\Controllers\Inventory;

use App\Admin\Ajax\Inventory\TransferAuditAjax;
use App\Models\Inventory\TransferAudit;
use App\Util\ListPermission;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
class TransferAuditController extends AdminController{

    protected $title = '库存挪用审批';

    protected $filters = [
        'sku' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['sku'] = $this->filters['sku'];
        return view('inventory.transfer-audit.index', compact('paginator','filtersBlade','action'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = TransferAudit::query()->where('status',1)->orderBy('id', 'DESC');
        $query = ListPermission::oArea($query);
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new TransferAuditAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }
}
